package com.lmh.gpt.demo.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

import com.lmh.gpt.demo.model.GPTResponse;
import com.lmh.gpt.demo.model.Response;
import com.lmh.gpt.demo.service.ChatGptService;
import com.lmh.gpt.demo.service.ContextService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@RestController
public class OpenAIController {
    @Autowired
    private ChatGptService chatGptService;

    @Autowired
    private ContextService contextService;

    @Autowired
    private RedisTemplate redisTemplate;

    @GetMapping("/index")
    public ModelAndView index() {
        ModelAndView modelAndView = new ModelAndView("talk");
        return modelAndView;
    }

    @GetMapping("/chat")
    public String chatWithGPT(@RequestParam("q") String question) throws JsonProcessingException {
        String completionResponse = null;
        // 从Redis中获取上下文
        ArrayList<String> context = retrieveContextFromRedis();
        if(context.isEmpty()){
            completionResponse = contextService.sendRequestWithContext(question);
            // 将问题和响应添加到上下文中
            String contextEntry = question + ";" + completionResponse;
            context.add(contextEntry);
            // 将更新后的上下文保存到Redis中
            saveContextToRedis(context);
        }else{
            completionResponse = contextService.sendRequestWithContext(question,context);

        }

        // 将历史对话添加到响应中
        // 将历史对话添加到响应中
        List<Response> chatHistory =  getChatHistoryResponse(context);

        // 构建ChatResponse对象
        GPTResponse GPTResponse = new GPTResponse();
        GPTResponse.setChatHistory(chatHistory);
        GPTResponse.setResponse(completionResponse);

        ObjectMapper objectMapper = new ObjectMapper();
        String jsonResponse = null;
        if (completionResponse != null) {
            // 将响应内容转换为JSON字符串
            jsonResponse = objectMapper.writeValueAsString(GPTResponse);
            // 将历史对话和响应合并为最终响应

            return jsonResponse;
        } else {
            // 将历史对话作为响应返回
            // 将历史对话作为响应返回
            jsonResponse = objectMapper.writeValueAsString(chatHistory);
            return jsonResponse;
        }

    }
    private ArrayList<String> retrieveContextFromRedis() {
        ValueOperations<String, String> valueOps = redisTemplate.opsForValue();
        String contextJson = valueOps.get("chat_context");
        if (contextJson != null) {
            try {
                return new ArrayList<>(Arrays.asList(contextJson.split(";")));
            } catch (Exception e) {
                // 处理解析异常
                e.printStackTrace();
            }
        }
        return new ArrayList<>();
    }
    private void saveContextToRedis(List<String> context) {
        String contextJson = String.join(";", context);
        ValueOperations<String, String> valueOps = redisTemplate.opsForValue();
        valueOps.set("chat_context", contextJson);
    }
    private List<Response> getChatHistoryResponse(ArrayList<String> context) {
        List<Response> chatHistory = new ArrayList<>();
        for (String entry : context) {
            String[] parts = entry.split(";");
            if (parts.length == 2) {
                String sender = parts[0];
                String content = parts[1];
                chatHistory.add(new Response(sender, content));
            }
        }
        return chatHistory;
    }
    @PostMapping("/clear-context")
    public void clearContext() {
        clearContextInRedis();
    }

    private void clearContextInRedis() {
        redisTemplate.delete("chat_context");
    }

}
